import {
  Router
} from 'express'
const router = Router()
import config from 'config'
import _ from 'lodash'
import util from '../../util'
import user from './user'
import categorys from './categorys'
import tags from './tags'
import articles from './articles'
import multer from 'multer'
import cos from '../../libs/cos'
import fs from 'fs'
import { throws } from 'assert';
let isPod = process.env.NODE_ENV=='production'
let upload = multer();
router.use((req, res, next) => {
  req.body = _.assign({}, _.cloneDeep(req.query), _.cloneDeep(req.body));
  next()
})
let checklogin = (req, res, next) => {
  if(!isPod){
    next();
  }else{
    if (req.session && req.session.user && req.session.user.id) {
      return res.redirect(`${config.get('admin.route')}/dashboard`)
    } else {
      next();
    }
  }
}
let checkNoLogin = (req, res, next) => {
  if(!isPod){
    next();
  }else{
    if (req.session && req.session.user && req.session.user.id) {
      next();
    } else {
      return res.redirect(`${config.get('admin.route')}/login`)
    }
  }
  
}
router.get('/', (req, res, next) => {
  return res.redirect(`${config.get('admin.route')}/login`)
})
router.get('/login', checklogin, (req, res, next) => {
  res.render('login', {
    'module_dir': config.get('admin.route')
  })
})
router.get('/register', checklogin, (req, res, next) => {
  res.render('register', {
    'module_dir': config.get('admin.route')
  })
})
router.get('/dashboard', checkNoLogin,(req, res, next) => {
  res.render('dashboard', {
    'module_dir': config.get('admin.route')
  })
})
router.post('/upload/file', upload.single('file'), async (req, res, next) => {
  // 引入模块
  let file = req.file;
  let type = file.mimetype.split('/')[1];
  let Key = `/upload/${util.getDateDir('months')}${util.createNoncestr()+util.getTimeString()}.${type}`
  let params = {
    Bucket: `blog-${config.get('cos.APPID')}`,
    /* 必须 */
    Region: 'ap-chengdu',
    /* 必须 */
    Key,
    /* 必须 */
    ContentLength: file.size,
    /* 必须 */
    Body: file.buffer,
    /* 必须 */
    onProgress: function (progressData) {
      console.log(progressData);
    },
  };
  let result =null ;
  try{
    result = await cos.putObject(params);
  }catch(err){
    return res.send(util.resError({
      msg:err
    }))
  }

  return res.send(util.resSuccess({
    data: result
  }))
  
})
router.use('/api',user)
router.use('/categorys', checkNoLogin,categorys)
router.use('/tags',checkNoLogin,tags)
router.use('/articles',checkNoLogin,articles)
export default router